<template>
  <t-row class="row" style="backgroundcolor: #f3f3f3">
    <t-col :span="8" :push="2">
      <card isCustomHeader :hoverShadow="false">
        <template #header>
          <b class="arrow" @click="$router.push('/dashboard')"
            ><arrow-left-icon style="width: 30px" /> <span>个人账户</span>
          </b>
        </template>
        <t-form labelAlign="top" style="padding: 0 10% 2%">
          <t-form-item label="基本信息" name="name">
            <div class="inp">
              <t-avatar size="100px" class="avatar" :image="avatar"></t-avatar>
            </div>
            <upload v-model="files" theme="custom" class="upload-pic" @returnRes="editAvatar">
              <template slot="pic">
                <t-button theme="default">上传</t-button>
              </template>
            </upload>
          </t-form-item>

          <t-form-item label="用户名称" name="name">
            <t-input placeholder="请输入内容" class="inp" v-model="name" clearable :readonly="idEditname" />
            <t-button
              theme="default"
              v-if="isEditUserName"
              @click="(isEditUserName = !isEditUserName), (idEditname = !idEditname)"
              >编辑</t-button
            >
            <t-space v-else class="btns">
              <t-button @click="EditUserName(0)">取消</t-button>
              <t-button @click="EditUserName(1)">确定</t-button>
            </t-space>
          </t-form-item>
          <t-form-item label="所属企业" name="college">
            <t-select :placeholder="userInfo.orgName" disabled> </t-select>
          </t-form-item>
          <t-form-item label="用户角色" name="college">
            <t-select :placeholder="userInfo.role" disabled> </t-select>
          </t-form-item>
          <div class="safeSet">安全设置</div>
          <t-form-item label="账户密码" name="tel">
            <t-input placeholder="******" class="inp" readonly>
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
            <t-button theme="default" @click="passwordVisible = true">变更</t-button>
          </t-form-item>
          <t-form-item label="邮箱" name="tel">
            <t-input placeholder="请输入内容" class="inp" readonly v-model="userInfo.email">
              <template #prefix-icon>
                <mail-icon />
              </template>
            </t-input>
            <t-button theme="default" @click="emailVisible = true">变更</t-button>
          </t-form-item>
          <t-form-item label="手机号码" name="tel">
            <t-input placeholder="请输入内容" class="inp" readonly v-model="userInfo.mobile">
              <template #prefix-icon>
                <mobile-icon />
              </template>
            </t-input>
            <t-button theme="default" @click="phoneVisible = true">变更</t-button>
          </t-form-item>
        </t-form>
      </card>
    </t-col>
    <!-- 修改密码 -->sswordClosesswordClose
    <t-dialog
      header="变更密码"
      :visible="passwordVisible"
      :onClose="passwordClick"
      :onConfirm="passwordClick"
      :closeOnOverlayClick="false"
    >
      <div slot="body">
        <t-form labelAlign="top" requiredMark>
          <t-form-item label="原密码">
            <t-input placeholder="请输入内容" v-model="oldPassword" type="password">
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
          </t-form-item>
          <t-form-item label="新密码">
            <t-input placeholder="请输入内容" v-model="newPassword1" type="password" :maxlength="20">
              <template #prefix-icon>
                <lock-on-icon />
              </template>
              <template #tips>长度为 8-20 个字符，需同时包含数字、字母以及特殊符号（!@#$%^&*()等非空格）</template>
            </t-input>
          </t-form-item>
          <t-form-item label="重复新密码" style="margin-top: 50px">
            <t-input placeholder="请输入内容" v-model="newPassword2" type="password" :maxlength="20">
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
          </t-form-item>
        </t-form>
      </div>
      <template #footer>
        <t-space class="footer">
          <t-button @click="passwordClick(0)">取消</t-button>
          <t-button @click="passwordClick(1)">确定</t-button>
        </t-space>
      </template>
    </t-dialog>
    <!-- 修改邮箱 -->
    <t-dialog :visible="emailVisible" :onClose="emailClick" :closeOnOverlayClick="false" :onConfirm="passwordClick">
      <div slot="header">
        <span style="vertical-align: middle" v-if="isEmailNext">身份验证</span>
        <span style="vertical-align: middle" v-else>绑定新邮箱</span>
      </div>
      <div slot="body">
        <t-form labelAlign="top" requiredMark>
          <t-form-item label="新邮箱" v-show="!isEmailNext">
            <t-input placeholder="请输入内容" v-model="newEmail" />
          </t-form-item>
          <p>为了保护账号安全，请先完成邮箱验证（andy.shi@pis360.com）：</p>
          <div class="verifyCode">
            <t-input placeholder="请输入内容" style="width: 70%" v-model="inputEmailCode">
              <template #prefix-icon>
                <mail-icon />
              </template>
            </t-input>
            <t-button :disabled="countDown > 0" @click="sendEmailCode" class="verify-btn">
              {{ countDown == 0 ? '发送验证码' : `${countDown}秒后可重发` }}
            </t-button>
          </div>
        </t-form>
      </div>
      <template #footer>
        <t-space class="footer">
          <t-button @click="emailClick(0)">取消</t-button>
          <t-button @click="emailNextClick" v-show="isEmailNext">下一步</t-button>
          <t-button @click="emailClick(1)" v-show="!isEmailNext">确定</t-button>
        </t-space>
      </template>
    </t-dialog>
    <!-- 修改手机 -->
    <t-dialog :visible="phoneVisible" :onClose="phoneClick" :closeOnOverlayClick="false" :onConfirm="phoneClick">
      <div slot="header">
        <span style="vertical-align: middle" v-if="isPhoneNext">身份验证</span>
        <span style="vertical-align: middle" v-else>绑定新手机号码</span>
      </div>
      <div slot="body">
        <t-form labelAlign="top" requiredMark>
          <t-form-item label="新手机号码" v-show="!isPhoneNext">
            <t-input placeholder="请输入内容" v-model="newPhone">
              <template #prefix-icon>
                <mobile-icon />
              </template>
            </t-input>
          </t-form-item>
          <p>为了保护账号安全，请先完成手机号码验证（1866666666）：</p>
          <div class="verifyCode">
            <t-input placeholder="请输入内容" style="width: 70%" v-model="inputPhoneCode" />
            <t-button :disabled="countDown > 0" @click="sendPhoneCode" class="verify-btn">
              {{ countDown == 0 ? '发送验证码' : `${countDown}秒后可重发` }}
            </t-button>
          </div>
        </t-form>
      </div>
      <template #footer>
        <t-space class="footer">
          <t-button @click="phoneClick(0)">取消</t-button>
          <t-button @click="phoneNextClick" v-show="isPhoneNext">下一步</t-button>
          <t-button @click="phoneClick(1)" v-show="!isPhoneNext">确定</t-button>
        </t-space>
      </template>
    </t-dialog>
  </t-row>
</template>

<script>
import Card from '@/components/Card/index.vue';
import { FILE_URL_PREFIX } from '@/constants';
import Upload from '@/components/Upload/index.vue';
import { mapState } from 'vuex';
import { ArrowLeftIcon, LockOnIcon, MailIcon, MobileIcon } from 'tdesign-icons-vue';
import CryptoJS from 'crypto-js';
import {
  modifyPassword,
  emailVerificationCode,
  verificationCode,
  verifiCode,
  editMobile,
  editUserName,
} from '@/service/login/index';
import { requestEditAvatar } from '@/service/upload/index';

export default {
  components: {
    Card,
    ArrowLeftIcon,
    LockOnIcon,
    MailIcon,
    MobileIcon,
    Upload,
  },
  data() {
    return {
      files: [], // 头像文件
      avatar: '',
      autoUpload: false,
      idEditname: true, // 用户名称是否只可读
      isEditUserName: true,
      name: '',
      passwordVisible: false, // 修改密码对话框
      emailVisible: false, // 修改邮箱对话框
      phoneVisible: false, // 修改手机号对话框
      // 账户密码相关的数据
      oldPassword: '',
      newPassword1: '',
      newPassword2: '',
      // 邮箱相关的数据
      isEmailNext: true, // 是否在下一步 是的话就显示新邮箱的输入框
      isEmailRight: false, // 邮箱验证码是否正确
      inputEmailCode: '', // 用户输入的邮箱验证码
      newEmail: '', // 新邮箱

      // 手机相关的数据
      isPhoneNext: true, // 是否在下一步 是的话就显示新电话的输入框
      isPhoneRight: false, // 邮箱验证码是否正确
      inputPhoneCode: '', // 用户输入的手机验证码
      newPhone: '', // 新手机号
      // 验证码倒计时
      countDown: 0,
      intervalTimer: null,
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
    // headerName: {
    //   get() {
    //     return this.userInfo.name;
    //   },
    //   set(newVal) {
    //     this.userInfo.name = newVal;
    //   },
    // },
  },
  beforeDestroy() {
    clearInterval(this.intervalTimer);
  },
  mounted() {
    this.name = this.userInfo.name;
    this.avatar = this.userInfo.avatar || 'https://tdesign.gtimg.com/site/avatar.jpg';
  },
  methods: {
    // 修改用户名字
    async EditUserName(val) {
      this.idEditname = !this.idEditname;
      // 如果val===1 那么就是点击确认，要发请求，修改用户名称
      if (val) {
        if (this.name.trim() === '') {
          this.$message.warning('账号名不能为空');
          this.idEditname = !this.idEditname;
          return;
        }
        await editUserName({ id: this.userInfo.id, name: this.name });
        this.userInfo.name = this.name;

        this.isEditUserName = true;

        return;
      }
      this.name = this.userInfo.name;

      this.isEditUserName = true;
    },
    // 修改密码
    async passwordClick(val) {
      // 如果val===1 那么就是点击确认，要发请求，修改用户名称 CryptoJS.MD5(this.formData.password).toString()

      if (val === 1) {
        if (!this.oldPassword) this.$message.warning('请输入原密码');
        else if (!this.newPassword1) this.$message.warning('请输入新密码');
        else if (!this.newPassword2) this.$message.warning('请输入新密码');
        else if (this.newPassword2 !== this.newPassword1) this.$message.warning('新密码不一致');
        else if (!this.testNewPassword(this.newPassword2))
          this.$message.warning('您的密码复杂度太低（密码中必须包含字母、数字、特殊字符）');
        else {
          const res = await modifyPassword({
            newPassword: CryptoJS.MD5(this.newPassword2).toString(),
            oldPassword: CryptoJS.MD5(this.oldPassword).toString(),
          });
          if (res.code === 200) {
            this.$message.success(res.message);
            this.newPassword1 = '';
            this.newPassword2 = '';
            this.oldPassword = '';
            this.passwordVisible = false;
          }
        }
        return;
      }
      this.passwordVisible = false;
    },
    // 测试新密码是否合格
    testNewPassword(newPassword) {
      const pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}');
      return pwdRegex.test(newPassword);
    },
    // 发送邮箱验证码
    async sendEmailCode() {
      // 如果是发送新邮箱的验证码
      if (this.newEmail) {
        const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if (!email.test(this.newEmail)) {
          this.$message.error('邮箱格式不正确');
          return;
        }
        if (this.isBusinessEmail(this.newEmail)) {
          this.$message.error('请输入正确的企业邮箱');
          return;
        }
      }

      // 验证码倒计时
      this.countDown = 60;
      this.intervalTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else {
          clearInterval(this.intervalTimer);
          this.countDown = 0;
        }
      }, 1000);

      await emailVerificationCode({ email: this.newEmail || this.userInfo.email });
    },
    // 邮箱的下一步按钮
    async emailNextClick() {
      if (this.countDown === 0) {
        this.$message.warning('请发送验证码');
        return;
      }
      if (!this.inputEmailCode) {
        this.$message.warning('请输入邮箱验证码');
        return;
      }
      const res = await verifiCode({ code: this.inputEmailCode, inputContent: this.userInfo.email });
      if (res.code !== 200) return;
      this.$message.success('验证码正确');
      this.countDown = 0;
      this.isEmailNext = false;
      this.inputEmailCode = null;
    },
    // 修改邮箱
    async emailClick(val) {
      if (val === 1) {
        const res = await editMobile({ code: this.inputEmailCode, inputContent: this.newEmail });
        if (res.code !== 200) return;

        this.$message.success('修改成功');
        this.userInfo.email = this.newEmail;
        this.newEmail = '';
      }
      this.countDown = 0;
      this.inputEmailCode = null;
      this.emailVisible = false;
      this.isEmailNext = true;
    },
    // 发送手机验证码
    async sendPhoneCode() {
      if (this.newPhone) {
        const phoneNumber = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
        if (!phoneNumber.test(this.userInfo.mobile)) {
          this.$message.error('手机号格式不正确');
          return false;
        }
      }

      // 验证码倒计时
      this.countDown = 60;
      this.intervalTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else {
          clearInterval(this.intervalTimer);
          this.countDown = 0;
        }
      }, 1000);

      await verificationCode({ phone: this.newPhone || this.userInfo.mobile });
    },
    // 手机的下一步按钮
    async phoneNextClick() {
      if (this.countDown === 0) {
        this.$message.warning('请发送验证码');
        return;
      }
      if (!this.inputPhoneCode) {
        this.$message.error('请输入手机验证码');
        return;
      }
      const res = await verifiCode({ code: this.inputPhoneCode, inputContent: this.userInfo.mobile });
      if (res.code !== 200) return;
      this.$message.success('验证码正确');
      this.countDown = 0;
      this.isPhoneNext = false;
      this.inputPhoneCode = null;
    },
    // 修改手机
    async phoneClick(val) {
      if (val === 1) {
        const res = await editMobile({ code: this.inputPhoneCode, inputContent: this.newPhone });
        if (res.code !== 200) return;

        this.$message.success('修改成功');
        this.newPhone = '';
        this.userInfo.mobile = this.newPhone;
      }
      this.countDown = 0;
      this.inputPhoneCode = null;
      this.phoneVisible = false;
      this.isPhoneNext = true;
    },
    // 是否是企业邮箱
    isBusinessEmail(email) {
      const usualEmail = ['163.com', '126.com', 'qq.com', 'gmail.com', 'yeah.com', 'sina.com', 'hotmail.com'];
      const newEmail = email.slice(email.length - 11, email.length);
      return usualEmail.some((item) => {
        if (newEmail.indexOf(item) >= 0) {
          return item;
        }
        return false;
      });
    },
    // 头像上传 尺寸的限制
    beforeUpload(file) {
      if (file.size > 5 * 1024 * 1024) {
        this.$message.warning('上传的图片不能大于5M');
        return false;
      }
      return true;
    },
    // 上传头像失败
    handleFail({ file }) {
      this.$message.error(`头像文件 ${file.name} 上传失败`);
    },
    async editAvatar(path) {
      if (!path) return;
      if (!this.isImageType(path)) {
        this.files.pop();
        this.$message.warning('请上传图片类型');
        return;
      }
      path = FILE_URL_PREFIX + path;
      const res = await requestEditAvatar({ id: this.userInfo.id, avatar: path });
      if (res.code === 200) {
        this.$message.success(res.message);
        this.userInfo.avatar = path;
        this.avatar = path;
        this.files.shift();
      }
    },
    isImageType(str) {
      const type = str.split('.').pop();
      // toLowerCase() 将字符串转换为小写，返回一个新的字符串
      return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(type.toLowerCase()) !== -1;
    },
  },
};
</script>

<style lang="less" scoped>
.row {
  margin-top: 2%;
  .safeSet {
    font-size: 16px;
    font-weight: 600;
    line-height: 24px;
  }
  .arrow {
    margin-left: -10px;
    line-height: 10px;
  }
  .t-form__controls-content {
    display: flex;
    justify-content: space-between;
  }
  .inp {
    width: 70%;
    margin-right: 30%;
  }
  .avatar {
    width: 60%;
    margin-right: 30%;
  }
  .footer {
    display: flex;
    justify-content: center;
  }
  .verifyCode {
    display: flex;
    justify-content: space-between;
  }
  p {
    //styleName: Body/Small;
    font-family: PingFang SC;
    font-size: 12px;
    font-weight: 300;
    padding-bottom: 5px;
  }
}
/deep/.t-upload__dragger {
  border: none;
  height: 65px;
  justify-content: flex-end;
  padding: 0 !important;
  width: 100%;
}
</style>
